package com.zrkizzy.seckill.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 *
 * @author zhangrongkang
 * @since 2023/4/3
 */
public class DbUtil {

    /**
     * 建立数据库连接
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() throws Exception {
        // 定义数据库连接参数
        String url = "jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        // 用户名
        String username = "root";
        String password = "123456";
        String driver = "com.mysql.cj.jdbc.Driver";
        // 加载驱动
        Class.forName(driver);
        // 根据连接参数返回连接对象
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 关闭SQL相关资源
     *
     * @param preparedStatement 预编译对象
     * @throws SQLException SQL异常
     */
    public static void close(PreparedStatement preparedStatement) throws SQLException {
        if (null != preparedStatement) {
            preparedStatement.clearParameters();
            preparedStatement.close();
        }
    }

}
